package cn.yj.common;

import cn.yj.commons.utils.StringUtils;
import cn.yj.tools.readconfig.PropertiesUtils;
import com.google.zxing.WriterException;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Coordinate;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * 水印处理
 *
 * @author 永健
 * @since 2021-07-08 14:42
 */
public class ImageUtils {

    /**
     * @param imgBase64 要加水印的图片
     * @param target
     *
     * @throws IOException
     */
    public static String addImageWaterMark(String imgBase64, File target) throws IOException {
        BufferedImage bufferedImage = base64ToBufferedImage(imgBase64);
        BufferedImage markImage = ImageIO.read(target);

        markImage=Thumbnails.of(markImage).size(120,120).asBufferedImage();

        BufferedImage result =
                Thumbnails.of(bufferedImage).size(bufferedImage.getWidth(), bufferedImage.getHeight()) // 大小
                .watermark(Positions.BOTTOM_RIGHT, markImage, Float.parseFloat(PropertiesUtils.getStringValue("school-cbd"
                        + ".water-img-opacity", "0.3")))  // 0.5f表示透明度，最大值为1
                .outputQuality(1)// 图片质量，最大值为1
                .asBufferedImage();
        return getBufferedImageToBase64(result);
    }


    private static String addImageWaterMark(BufferedImage bufferedImage, File target, float v) throws IOException {
        BufferedImage image = ImageIO.read(target);
        BufferedImage result =
                Thumbnails.of(bufferedImage).size(bufferedImage.getWidth(), bufferedImage.getHeight()) // 大小
                .watermark(Positions.BOTTOM_RIGHT, image, v)  // 0.5f表示透明度，最大值为1
                .outputQuality(1)   // 图片质量，最大值为1
                .asBufferedImage();
        return getBufferedImageToBase64(result);
    }


    /**
     * 生成邀请海报
     *
     * @param userInviteCode 用户邀请码
     */
    public static String addInviteCodeMark(String userInviteCode) throws IOException, WriterException {
        ByteArrayOutputStream qrGen = QrUtils.createQrGen(PropertiesUtils.getStringValue("school-cbd" + ".mini-server"
                + "-domain").concat(userInviteCode));
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(qrGen.toByteArray());
        BufferedImage qrImg = ImageIO.read(byteArrayInputStream);

        BufferedImage bufferedImage =
                ImageIO.read(new File(PropertiesUtils.getStringValue("school-cbd" + ".posters" + "-img-path")));
        Thumbnails.of(bufferedImage).size(bufferedImage.getWidth(), bufferedImage.getHeight()) // 大小
                .watermark(Positions.CENTER, qrImg, 1)  // 0.5f表示透明度，最大值为1
                .outputQuality(1)   // 图片质量，最大值为1
                .toFile(System.getProperty("user.dir").concat("/poster.jpg"));
        File posterFile = new File(System.getProperty("user.dir").concat("/poster.jpg"));
        String posterBase64 = file2Base64(posterFile);
        posterFile.delete();
        return posterBase64;
    }



    private static String getBufferedImageToBase64(BufferedImage bufferedImage) throws IOException {
        String imageFormatName = "jpg";
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imageFormatName, stream);
        return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(stream.toByteArray());
    }

    public static String file2Base64(File file) {
        if (file == null) {
            return null;
        }
        String base64 = null;
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            byte[] buff = new byte[fin.available()];
            fin.read(buff);
            base64 = Base64.getEncoder().encodeToString(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "data:image/jpeg;base64," + base64;
    }

    /**
     * base64 编码转换为 BufferedImage
     *
     * @param base64
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        try {
            if (StringUtils.isBlank(base64)) {
                return null;
            }
            base64 = base64.substring(base64.indexOf(",") + 1);
            byte[] bytes1 = Base64.getDecoder().decode(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException, WriterException {
    }
}
